/* tslint:disable:typedef */
import {ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild} from '@angular/core';
import {MyTableConfig} from '../../../share/components/ant-table/ant-table.component';
import {PageHeaderType} from '../../../share/components/page-header/page-header.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {Router} from '@angular/router';
import {NzMessageService} from 'ng-zorro-antd/message';
import {NzTableQueryParams} from 'ng-zorro-antd/table';
import {GoBackParam, OptionsInterface, PageTypeEnum, SearchCommonVO} from '../../../core/services/types';
import {finalize} from 'rxjs/operators';
import {TestQuestionListModel, TestQuestionService} from '../../../core/services/http/test-question/test-question.service';
import {MapPipe, MapSet} from '../../../share/pipes/map.pipe';
import {ActionCode} from 'src/app/configs/actionCode';

interface SearchParam {
  type: string;
  questionBankId: number;
  content: string;
}

@Component({
  selector: 'app-test-question',
  templateUrl: './test-question.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TestQuestionComponent implements OnInit {
  @ViewChild('operationTpl', {static: true}) operationTpl!: TemplateRef<any>;
  ActionCode = ActionCode;
  searchParam: Partial<SearchParam> = {};
  actionCodeObj = {
    add: ActionCode.TestQuestionAdd,
    del: ActionCode.TestQuestionDel,
  };
  currentPage: number;
  pageTypeEnum = PageTypeEnum;
  tableConfig!: MyTableConfig;
  itemId!: number;
  pageHeaderInfo: Partial<PageHeaderType> = {
    title: '试题管理',
    breadcrumb: ['考试教育', '试题管理']
  };
  dataList: TestQuestionListModel[] = [];
  checkedCashArray: TestQuestionListModel[] = [];
  testQuestionOptions: OptionsInterface[] = [];
  listOfOption: OptionsInterface[] = [];

  constructor(private dataService: TestQuestionService, private modalSrv: NzModalService, private cdr: ChangeDetectorRef,
              private router: Router, private message: NzMessageService) {
    this.currentPage = this.pageTypeEnum.List;
  }

  selectedChecked(e: TestQuestionListModel[]): void {
    this.checkedCashArray = [...e];
  }

  allDel(): void {
    if (this.checkedCashArray.length > 0) {
      this.modalSrv.confirm({
        nzTitle: '确定要删除吗？',
        nzContent: '删除后不可恢复',
        nzOnOk: () => {
          const tempArrays: number[] = [];
          this.checkedCashArray.forEach((item) => {
            tempArrays.push(item.id);
          });
          this.tableLoading(true);
          this.dataService.delTestQuestion(tempArrays).subscribe(() => {
            if (this.dataList.length === 1) {
              this.tableConfig.pageIndex--;
            }
            this.getDataList();
            this.checkedCashArray = [];
          });
        }
      });
    } else {
      this.message.error('请勾选数据');
      return;
    }
  }

  getDataList(e?: NzTableQueryParams): void {
    this.tableConfig.loading = true;
    const params: SearchCommonVO<any> = {
      pageSize: this.tableConfig.pageSize!,
      pageNum: e?.pageIndex || this.tableConfig.pageIndex!,
      filters: this.searchParam
    };
    this.dataService.getTestQuestionList(params).pipe(finalize(() => {
      this.tableLoading(false);
    })).subscribe((data => {
      const {list, total, pageNum} = data;
      this.dataList = [...list];
      this.tableConfig.total = total!;
      this.tableConfig.pageIndex = pageNum!;
      this.tableLoading(false);
      this.checkedCashArray = [...this.checkedCashArray];
    }));
  }

  /*返回功能*/
  async returnToList(e?: GoBackParam) {
    this.currentPage = this.pageTypeEnum.List;
    if (!!e && e.refesh) {
      await this.getDataList({pageIndex: e.pageNo} as NzTableQueryParams);
    }
  }

  /*题库下拉请求数据*/
  selectList(): Promise<any> {
    return new Promise(resolve => {
      this.dataService.getQuestionBankSelectList({pageSize: 0, pageNum: 0}).subscribe(datas => {
        datas.list.forEach(item => {
          this.listOfOption.push({value: item.id, label: item.name});
        });
        resolve();
      });
    });
  }

  /*重置*/
  resetForm(): void {
    this.searchParam = {};
    this.getDataList();
  }

  // 触发表格变更检测
  tableChangeDectction(): void {
    // 改变引用触发变更检测。
    this.dataList = [...this.dataList];
    this.cdr.detectChanges();
  }

  tableLoading(isLoading: boolean): void {
    this.tableConfig.loading = isLoading;
    this.tableChangeDectction();
  }

  /*新增*/
  add(): void {
    this.itemId = 0;
    this.currentPage = this.pageTypeEnum.AddOrEdit;
  }

  /*编辑修改*/
  edit(id: number): void {
    this.itemId = id;
    this.currentPage = this.pageTypeEnum.AddOrEdit;
  }

  /*删除*/
  del(id: number): void {
    this.modalSrv.confirm({
      nzTitle: '确定要删除吗？',
      nzContent: '删除后不可恢复',
      nzOnOk: () => {
        this.tableLoading(true);
        this.dataService.delTestQuestion([id]).subscribe(() => {
          if (this.dataList.length === 1) {
            this.tableConfig.pageIndex--;
          }
          this.getDataList();
          this.checkedCashArray.splice(this.checkedCashArray.findIndex(item => item.id === id), 1);
        }, error => this.tableLoading(false));
      }
    });
  }

  // 修改一页几条

  changePageSize(e: number): void {
    this.tableConfig.pageSize = e;
  }

  async ngOnInit(): Promise<any> {
    this.initTable();
    await this.selectList();
    this.testQuestionOptions = [...MapPipe.transformMapToArray(MapSet.topicType)];
  }

  private initTable(): void {
    this.tableConfig = {
      showCheckbox: true,
      headers: [
        {
          title: '题目类型',
          field: 'type',
          pipe: 'topicType',
          width: 30,
        },
        {
          title: '题目内容',
          width: 250,
          field: 'content',
        },
        {
          title: '创建时间',
          width: 60,
          field: 'createTime',
          pipe: 'date:yyyy-MM-dd HH:mm'
        },
        {
          title: '操作',
          tdTemplate: this.operationTpl,
          width: 60,
          fixed: true
        }
      ],
      total: 0,
      loading: true,
      pageSize: 10,
      pageIndex: 1,
    };
  }

}

